﻿using AutoMapper;
using FreeSql;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Identity;
using System.Reflection;

namespace Darius.API.Application.Commands
{
    public class UsersCreateHandler : IRequestHandler<UsersCreateCommand, ResultT<UsersRoleDto>>
    {

        private readonly IBaseRepositorys<Users> usersRep;
        private readonly IBaseRepositorys<UserRole> userolesRep;
        private readonly IMapper mapper;
        private readonly ILogger<RoleCreateHandler> logger;

        public UsersCreateHandler(IBaseRepositorys<Users> usersRep, IMapper mapper, ILogger<RoleCreateHandler> logger, IBaseRepositorys<UserRole> userolesRep)
        {
            this.usersRep = usersRep;
            this.mapper = mapper;
            this.logger = logger;
            this.userolesRep = userolesRep;
        }

        /// <summary>
        /// 用户角色添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultT<UsersRoleDto>> Handle(UsersCreateCommand request, CancellationToken cancellationToken)
        {
            var res = 0;
            try
            {
                var result = new ResultT<UsersRoleDto>() { Code = (int)CodeEnum.add };

                Users user = new Users()
                {
                    UserAccount = request.UserAccount,
                    UsersName = request.UsersName,
                    Gender = request.Gender,
                    UsersImage = request.UsersImage,
                    UsersDate = DateTime.Now,
                    CreateName = request.CreateName,
                    Pid = request.Pid,
                };
                res += usersRep.Add(user);
                //foreach (var item in request.RoleId)
                //{
                //    var list = usersRep.GetAll().Select(x => x.UsersId).ToList();
                //    int a = list.Max();
                //    var useroles = new UserRole()
                //    {
                //        UsersId = a,
                //        RoleId = item
                //    };
                //    res += userolesRep.Add(useroles);
                //}
                result.Messege = "添加成功";
                result.Code = res;
                logger.LogInformation(result.Messege);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加用户失败");
                return new ResultT<UsersRoleDto>() { Code = (int)CodeEnum.error, Messege = "添加角色权限失败" };
            }
            
        }
    }
}
